package com.ic.es.util;

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;

@Component
public class IndexCreationScheduler {

    private final RestHighLevelClient client;

    @Autowired
    public IndexCreationScheduler(RestHighLevelClient client) {
        this.client = client;
    }

    // 每天午夜执行一次
    @Scheduled(cron = "0 0 0 1 * ?")
//    @Scheduled(cron = "0 * * * * ?")
    public void scheduleIndexCreation() {
        LocalDate today = LocalDate.now();
        String indexName = "indexface-" + today.toString().replace("-", "");
        try {
            if (!client.indices().exists(new org.elasticsearch.client.indices.GetIndexRequest(indexName), RequestOptions.DEFAULT)) {
                CreateIndexRequest request = new CreateIndexRequest(indexName);
                // 设置索引配置
                request.settings(Settings.builder()
                        .put("index.number_of_shards", 1)
                        .put("index.number_of_replicas", 0)
                );
                // 可以在这里添加映射配置，如果需要的话

                CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
                if (createIndexResponse.isAcknowledged()) {
                    System.out.println("Index " + indexName + " created successfully");
                } else {
                    System.out.println("Failed to create index " + indexName);
                }
            } else {
                System.out.println("Index " + indexName + " already exists");
            }
        } catch (IOException e) {
            // 处理异常，例如记录日志
            e.printStackTrace();
        }
    }
}
